import { MyFileDir } from "@/model/init";
import { staticPath, staticPathName } from "../utils/const";
import path from "path";
import { Sequelize } from "sequelize";
import { getDir, operateFile } from "./dataInit";
import fs from "fs";
import { MyFileDirItf } from "@/interface/interface";

// await MyFileDir.update({path: Sequelize.literal(`CONCAT('${staticPathName}', path)` )}, {where: {}})
// await MyFileDir.update({path: Sequelize.fn('SUBSTRING', Sequelize.col('path'), 8) }, {where: {}})
// console.log("更新结束");
/**
 * @description: 监听文件变化，对数据库做出更改
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
export function watchFile() {
    return new Promise(async (resolve, reject) => {
        console.log("开始");
        // 传入的必须是根目录，否则会有脏数据
        await forEachFile(path.join(staticPath, "/陶帅的固态1"));
        resolve(true);
    });
}

function getRelativePath(filePath: string) {
    return filePath.replace("/" + staticPathName, "");
}

async function forEachFile(filePath: string) {
    let fileObj = await getFileObj(getRelativePath(filePath));
    if (fileObj) {
        if (!fileObj.isFile) {
            let dirs =  (await getDir( filePath )).filter( item => item !== "operateFileByWeb_server" )
            for (const dir of dirs) {
                let p = path.resolve( filePath, dir )
                let isExit = await getFileObj( p.replace("/"+ staticPathName, "") )
                if( isExit ){
                    await forEachFile( p )
                }else{
                    console.log(p, "不存在,父级id：",fileObj.id! );
                    await operateFile(p, fileObj.id! )
                }
            }
        } else {
        }
    } else {
        console.log(filePath);
        console.log("运行到这里了,确定地址，否则会有脏数据");
        // operateFile( filePath, 0 )
    }
}

async function getFileObj(path: string) {
    let obj = await MyFileDir.findOne({
        where: {
            path,
        },
    });
    if (obj) {
        return obj?.dataValues as MyFileDirItf;
    } else {
        return null;
    }
}
